package com.xoa.service.template.impl;

import com.alibaba.fastjson.JSONObject;
import com.xoa.dao.modulePriv.ModulePrivMapper;
import com.xoa.dao.template.TemplateModuleMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.department.Department;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.template.TemplateModule;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.service.template.TemplateService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.GetAttachmentListUtils;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TemplateServiceImpl implements TemplateService {

    @Resource
    private TemplateModuleMapper templateModuleMapper;

    @Resource
    private EnclosureService enclosureService;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private ModulePrivMapper modulePrivMapper;

    @Resource
    private UserPrivMapper userPrivMapper;

    /**
     * @作者：张航宁
     * @时间：2017/8/7
     * @介绍：根据条件分页查询数据
     * @参数：templateModule
     */
    @Override
    public ToJson<TemplateModule> queryTemplate(TemplateModule templateModule, Integer page, Integer pageSize, Boolean useFlag) {
        ToJson<TemplateModule> json = new ToJson<TemplateModule>();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            map.put("page", pageParams);
            map.put("type", templateModule.getType());
            map.put("categoryId", templateModule.getCategoryId());

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse");
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users sessionUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
            sessionUser = usersMapper.findUsersByuserId(sessionUser.getUserId());
            map.put("privUser", sessionUser.getUserId());//授权人员
            map.put("privRole", sessionUser.getUserPriv());//授权角色
            map.put("privOrg", sessionUser.getDeptId());//授权部门
            List<TemplateModule> list = templateModuleMapper.query(map);

            //List<TemplateModule> end = new ArrayList<TemplateModule>();//判断完权限最后的集合
            for (TemplateModule t : list) {
                // 用户
                if (!StringUtils.checkNull(t.getPrivUser())) {
                    String[] split = t.getPrivUser().split(",");
                    List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                    if (usersByUids != null && usersByUids.size() > 0) {
                        StringBuffer sb = new StringBuffer();
                        for (Users u : usersByUids) {
                            sb.append(u.getUserName() + ",");
                        }
                        t.setPrivUserName(sb.toString());
                    }
                } else {
                    t.setPrivUser("");
                    t.setPrivUserName("");


                }

                // 部门
                if (!StringUtils.checkNull(t.getPrivOrg())) {
                    String[] split = t.getPrivOrg().split(",");
                    List<Department> deptNameByIds = modulePrivMapper.getDeptNameByIds(split);
                    if (deptNameByIds != null && deptNameByIds.size() > 0) {
                        StringBuffer sb = new StringBuffer();
                        for (Department d : deptNameByIds) {
                            sb.append(d.getDeptName() + ",");
                        }
                        t.setPrivOrgName(sb.toString());
                    }
                } else {
                    t.setPrivOrg("");
                    t.setPrivOrgName("");
                }

                // 角色
                if (!StringUtils.checkNull(t.getPrivRole())) {
                    String[] split = t.getPrivRole().split(",");
                    List<UserPriv> privNameByIds = modulePrivMapper.getPrivNameByIds(split);
                    if (privNameByIds != null && privNameByIds.size() > 0) {
                        StringBuffer sb = new StringBuffer();
                        for (UserPriv up : privNameByIds) {
                            sb.append(up.getPrivName() + ",");
                        }
                        t.setPrivRoleName(sb.toString());
                    }
                } else {
                    t.setPrivRole("");
                    t.setPrivRoleName("");
                }

                if (!StringUtils.checkNull(t.getAttachmentId())&&!StringUtils.checkNull(t.getAttachmentName())){
                    try {
                        List<Attachment> l = GetAttachmentListUtils.returnAttachment(t.getAttachmentName(),t.getAttachmentId(),sqlType,"template");
                        t.setAttUrl(l.get(0).getAttUrl());
                    }catch (Exception e){
                        e.getStackTrace();
                    }

                }
                /*if (!StringUtils.checkNull(t.getPrivUser())){
                    String[] split1 = t.getPrivUser().split(",");
                    for (String list2:split1){
                        if (sessionUser.getUserId().equals(list2)){
                            end.add(t);
                        }
                    }
                }else if(!StringUtils.checkNull(t.getPrivOrg())){
                    String[] split2 = t.getPrivOrg().split(",");
                    for (String list3:split2){
                        if (sessionUser.getUserId().equals(list3)){
                            end.add(t);
                        }
                    }
                }else if(!StringUtils.checkNull(t.getPrivRole())){
                    String[] split3 = t.getPrivOrg().split(",");
                    for (String list4:split3){
                        if (sessionUser.getUserId().equals(list4)){
                            end.add(t);
                        }
                    }
                }*/
            }
            json.setTotleNum(pageParams.getTotal());
            json.setObj(list);
            //json.setObj(end);判断玩权限最后的
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    /**
     * @作者：张航宁
     * @时间：2017/8/7
     * @介绍：添加一个模板信息
     * @参数：template file
     */
    @Override
    public ToJson<TemplateModule> addTemplate(HttpServletRequest request,HttpServletResponse response, TemplateModule template, MultipartFile file) {
        ToJson<TemplateModule> json = new ToJson<TemplateModule>();
        try (ServletOutputStream out = response.getOutputStream();OutputStreamWriter ow = new OutputStreamWriter(out,"UTF-8")){
            // 获取当前登录用户信息
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users sessionUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
            // 设置创建时间
            template.setCreateTime((int) (System.currentTimeMillis() / 1000));
            // 设置创建人id
            template.setCreateUser(sessionUser.getUid());

            /*if (file != null) {
                MultipartFile[] files = {file};
                List<Attachment> template1 = enclosureService.upload(files, "xoa" + (String) request.getSession().getAttribute("loginDateSouse"), "template");
                if (template1 != null && template1.size() > 0) {
                    template.setAttUrl(template1.get(0).getAttUrl());
                }
            }*/
            template.setAttUrl("");//不在读写该字段
            templateModuleMapper.insertSelective(template);



            json.setObject(template);
            json.setMsg("ok");
            json.setFlag(0);

            response.setHeader("content-type", "text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");


            ow.write(JSONObject.toJSONString(json));
            ow.flush();
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    /**
     * @作者：张航宁
     * @时间：2017/8/7
     * @介绍：更新一个模板信息
     * @参数：template
     */
    @Override
    public ToJson<TemplateModule> updateTemplate(TemplateModule template, MultipartFile file, Integer deleteFlag, HttpServletRequest request, HttpServletResponse response) {
        ToJson<TemplateModule> json = new ToJson<TemplateModule>();
        try {
            if (deleteFlag == 0) {
                template.setAttUrl(null);
            }
            if (deleteFlag == 1) {
                template.setAttUrl("");
            }
            if (deleteFlag == 2) {
                if (file != null) {
                    MultipartFile[] files = {file};
                    List<Attachment> template1 = enclosureService.upload(files, "xoa" + (String) request.getSession().getAttribute("loginDateSouse"), "template");
                    if (template1 != null && template1.size() > 0) {
                        template.setAttUrl(template1.get(0).getAttUrl());
                    }
                }
            }
            templateModuleMapper.updateByPrimaryKeySelective(template);
            json.setMsg("ok");
            json.setFlag(0);

            response.setHeader("content-type", "text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream out = response.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(out,"UTF-8");

            ow.write(JSONObject.toJSONString(json));
            ow.flush();
            ow.close();

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    /**
     * @作者：张航宁
     * @时间：2017/8/7
     * @介绍：删除一条模板信息
     * @参数：id
     */
    @Override
    public ToJson<TemplateModule> deleteTemplate(Integer id) {
        ToJson<TemplateModule> json = new ToJson<TemplateModule>();
        try {
            if (id != null) {
                templateModuleMapper.deleteByPrimaryKey(id);
            }
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    /**
     * @作者：张航宁
     * @时间：2017/8/12
     * @介绍：根据权限获取模板信息
     * @参数：
     */
    @Override
    public ToJson<TemplateModule> queryTemplateByPriv(TemplateModule templateModule, Integer page, Integer pageSize, Boolean useFlag, HttpServletRequest request) {
        ToJson<TemplateModule> json = new ToJson<TemplateModule>();
        Map<String, Object> map = new HashMap<String, Object>();
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users sessionUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
            sessionUser = usersMapper.findUsersByuserId(sessionUser.getUserId());
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            map.put("page", pageParams);
            map.put("type", templateModule.getType());
            map.put("categoryId", templateModule.getCategoryId());
            map.put("userId",sessionUser.getUserId());
            map.put("deptId",sessionUser.getDeptId());
            map.put("userPriv",sessionUser.getUserPriv());
            List<TemplateModule> list = templateModuleMapper.queryByPriv(map);
            pageParams.setUseFlag(false);
            map.put("page", pageParams);
            List<TemplateModule> count = templateModuleMapper.queryByPriv(map);
            for (TemplateModule list1:list){//判断权限
                if (!StringUtils.checkNull(list1.getAttachmentId())&&!StringUtils.checkNull(list1.getAttachmentName())){
                    try {
                        List<Attachment> l = GetAttachmentListUtils.returnAttachment(list1.getAttachmentName(),list1.getAttachmentId(),sqlType,"template");
                        list1.setAttUrl(l.get(0).getAttUrl());
                    }catch (Exception e){
                        e.getStackTrace();
                    }

                }
            }
            map.remove("page");
            //Integer count = templateModuleMapper.queryCountByPriv(map);
            json.setTotleNum(count.size());
            json.setObj(list);
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }
    @Override
    public ToJson<TemplateModule> queryTemplateByPrivs(TemplateModule templateModule, Integer page, Integer pageSize, Boolean useFlag, HttpServletRequest request) {
        ToJson<TemplateModule> json = new ToJson<TemplateModule>();
        Map<String, Object> map = new HashMap<String, Object>();
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users sessionUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
            sessionUser = usersMapper.findUsersByuserId(sessionUser.getUserId());
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            map.put("page", pageParams);
            map.put("type", templateModule.getType());
            map.put("categoryId", templateModule.getCategoryId());
            map.put("userId",sessionUser.getUserId());
            map.put("deptId",sessionUser.getDeptId());
            map.put("userPriv",sessionUser.getUserPriv());
            List<TemplateModule> list = templateModuleMapper.queryByPrivs(map);

            pageParams.setUseFlag(false);
            map.put("page", pageParams);
            List<TemplateModule> count = templateModuleMapper.queryByPrivs(map);
            for (TemplateModule list1:list){
                if (!StringUtils.checkNull(list1.getAttachmentId())&&!StringUtils.checkNull(list1.getAttachmentName())){
                    try {
                        List<Attachment> l = GetAttachmentListUtils.returnAttachment(list1.getAttachmentName(),list1.getAttachmentId(),sqlType,"template");
                        list1.setAttUrl(l.get(0).getAttUrl());
                    }catch (Exception e){
                        e.getStackTrace();
                    }

                }
            }
            map.remove("page");
            //Integer count = templateModuleMapper.queryCountByPriv(map);
            json.setTotleNum(count.size());
            json.setObj(list);
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }
    //lsa添加，，模板管理不需要权限
    @Override
    public ToJson<TemplateModule> queryAll(TemplateModule templateModule, Integer page, Integer pageSize, Boolean useFlag) {
        ToJson<TemplateModule> json = new ToJson<TemplateModule>();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            map.put("page", pageParams);
            map.put("type", templateModule.getType());
            map.put("categoryId", templateModule.getCategoryId());

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse");
            List<TemplateModule> list = templateModuleMapper.queryAll(map);
            for (TemplateModule t : list) {
                // 用户
                if (!StringUtils.checkNull(t.getPrivUser())) {
                    String[] split = t.getPrivUser().split(",");
                    List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                    if (usersByUids != null && usersByUids.size() > 0) {
                        StringBuffer sb = new StringBuffer();
                        for (Users u : usersByUids) {
                            sb.append(u.getUserName() + ",");
                        }
                        t.setPrivUserName(sb.toString());
                    }
                } else {
                    t.setPrivUser("");
                    t.setPrivUserName("");


                }

                // 部门
                if (!StringUtils.checkNull(t.getPrivOrg())) {
                    String[] split = t.getPrivOrg().split(",");
                    List<Department> deptNameByIds = modulePrivMapper.getDeptNameByIds(split);
                    if (deptNameByIds != null && deptNameByIds.size() > 0) {
                        StringBuffer sb = new StringBuffer();
                        for (Department d : deptNameByIds) {
                            sb.append(d.getDeptName() + ",");
                        }
                        t.setPrivOrgName(sb.toString());
                    }
                } else {
                    t.setPrivOrg("");
                    t.setPrivOrgName("");
                }

                // 角色
                if (!StringUtils.checkNull(t.getPrivRole())) {
                    String[] split = t.getPrivRole().split(",");
                    List<UserPriv> privNameByIds = modulePrivMapper.getPrivNameByIds(split);
                    if (privNameByIds != null && privNameByIds.size() > 0) {
                        StringBuffer sb = new StringBuffer();
                        for (UserPriv up : privNameByIds) {
                            sb.append(up.getPrivName() + ",");
                        }
                        t.setPrivRoleName(sb.toString());
                    }
                } else {
                    t.setPrivRole("");
                    t.setPrivRoleName("");
                }

                if (!StringUtils.checkNull(t.getAttachmentId())&&!StringUtils.checkNull(t.getAttachmentName())){
                    try {
                        List<Attachment> l = GetAttachmentListUtils.returnAttachment(t.getAttachmentName(),t.getAttachmentId(),sqlType,"template");
                        t.setAttUrl(l.get(0).getAttUrl());
                    }catch (Exception e){
                        e.getStackTrace();
                    }

                }
            }
            json.setTotleNum(pageParams.getTotal());
            json.setObj(list);
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

}
